//
//  OSTool.m
//  UniversalApp
//
//  Created by 凯朱 on 2019/5/30.
//  Copyright © 2019 徐阳. All rights reserved.
//

#import "OSTool.h"
#import <Foundation/NSFileManager.h>
#import "OSLoginVC.h"
static  NSUInteger const kDefaultViewTag = 999999999;
static  NSInteger const kHudTag = 17884553612;
@interface OSTool()
@end

@implementation OSTool
/**
 window上展示toast提示
 
 @param message 提示文案
 */
+(void)showMsgOnWindowWithMsg:(NSString *)message{
    message = kLocalString(message);
    if (message.length == 0) return;
    //如果已经有toast弹窗了 暂时不立刻展示下一个弹窗
    UIView *messageView = [kAppWindow viewWithTag:540021];
    if (messageView){
        [messageView removeFromSuperview];
    }
    //展示toast提示
    CGSize size = STRING_SIZE_FONT(240, message, kFontMedium(16));
    messageView = [[UIView alloc] initWithFrame:CGRectMake(([[UIScreen mainScreen] bounds].size.width-(size.width+30))/2, (CGRectGetHeight(kAppWindow.bounds)-size.height-30)/2, size.width, size.height)];
    messageView.backgroundColor = [kHexColor(@"#000000") colorWithAlphaComponent:0.3];
    messageView.tag = 540021;
    messageView.layer.cornerRadius = 5.0f;
    [messageView.layer setMasksToBounds:YES];
    [kAppWindow addSubview:messageView];
    
    //整个屏幕居中对齐
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, CGRectGetWidth(messageView.bounds), CGRectGetHeight(messageView.bounds))];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.tag = 1000;
    [titleLabel setText:message];
    
    [titleLabel setFont:kFontMedium(16)];
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    [titleLabel setTextColor:OSWhiteColor];
    [titleLabel sizeToFit];
    titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
    titleLabel.numberOfLines = 0;
    [messageView addSubview:titleLabel];
    
    //限制最长长度
    if (CGRectGetWidth(titleLabel.bounds)>270-30)
    {
        messageView.frame = CGRectMake(kScreenWidth/2-135,(KScreenHeight-size.height-30)/2-30,270,size.height+30);
    }
    else
    {
        messageView.frame = CGRectMake((kScreenWidth - CGRectGetWidth(titleLabel.bounds)-30)/2,(KScreenHeight-CGRectGetHeight(titleLabel.bounds)-30)/2-30,CGRectGetWidth(titleLabel.bounds)+30,CGRectGetHeight(titleLabel.bounds)+30);
    }
    
    titleLabel.frame = CGRectMake(15, 15, size.width, size.height);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.2 animations:^{
            messageView.alpha = 1;
        } completion:^(BOOL finished) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [UIView animateWithDuration:0.3 animations:^{
                    messageView.alpha = 0;
                } completion:^(BOOL finished) {
                    [messageView removeFromSuperview];
                }];
            });
        }];
    });
}

+(void)pushToLogVc{
    OSLoginVC *logvc = [OSLoginVC new];
    [[self getCurrentUIVC].navigationController pushViewController:logvc animated:YES];
}

#pragma mark -
#pragma mark - ================<json转换相关>===============
/**
 字典转json字符串 - 无校验
 
 @param dic 字典
 @return json字符串
 */
+(NSString *)dictToJson:(NSDictionary *)dic
{
    if (dic == nil || ![dic isKindOfClass:[NSDictionary class]]) {
        return @"";
    }
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

/**
 数组转json字符串 - 无校验
 
 @param array 数组
 @return jsonStr
 */
+(NSString *)arrayToJson:(NSArray *)array
{
    if (array == nil || ![array isKindOfClass:[NSArray class]]) {
        return @"";
    }
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

/**
 字典或数组转字符串  代替方法  +(NSString *)systemUtilsDataToJson:(id)dicOrArr
 
 @param dicOrArr 字典或数组对象
 @return json字符串
 */
+(NSString *)objectToJson:(id)dicOrArr
{
    if ([dicOrArr isKindOfClass:[NSDictionary class]]) {
        return [self dictToJson:dicOrArr];
    }
    if ([dicOrArr isKindOfClass:[NSArray class]]) {
        return [self arrayToJson:dicOrArr];
    }
    
    return [NSString valueToString:dicOrArr];
}

/**
 json字符串转字典 - 有校验(解析失败或格式错误返回空字典)
 
 @param jsonStr json字符串
 @return 字典
 */
+(NSDictionary *)dictionaryWithJsonStr:(NSString *)jsonStr
{
    if ([jsonStr isKindOfClass:[NSDictionary class]]) return (NSDictionary *)jsonStr;
    
    if (jsonStr == nil || jsonStr.length == 0) return @{};
    
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    
    if(error) return @{};
    
    if ([dic isKindOfClass:[NSDictionary class]]) {
        return dic;
    }
    else{
        return @{};
    }
}

+(NSString *)locaStrWith:(NSString *)str{
    NSString *curLang = [[NSUserDefaults standardUserDefaults] valueForKey:@"curLang"];
    if (kSTRING(curLang).length == 0) curLang = @"th";
    NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:curLang ofType:@"lproj"]];
    NSString *localStr = NSLocalizedStringFromTableInBundle(str, @"Localizable", bundle, nil);
    if (kSTRING(localStr).length == 0) {
        return str;
    }
    return localStr;
}


/**
 json字符串转数组 - 有校验(解析失败或格式错误返回空字典)
 
 @param jsonStr json字符串
 @return 数组
 */
+(NSArray *)arrayWithJsonStr:(NSString *)jsonStr
{
    if ([jsonStr isKindOfClass:[NSArray class]]) return (NSArray *)jsonStr;
    
    if (jsonStr == nil || jsonStr.length == 0) return @[];
    
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    
    if(error) return @[];
    
    if ([array isKindOfClass:[NSArray class]]) {
        return array;
    }
    else{
        return @[];
    }
}

/**
 处理图片并且保存资源到本地 - 保存的为相对路径
 
 @param image 图片
 @return 图片文件名 - 相对路径
 */
+(NSString *)saveImageToLocalWithImage:(UIImage *)image{
    
    //压缩图片
    NSData *imageData = [self compressOriginalImage:image toMaxDataSizeKBytes:1024*1024];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:kDocImageName];
    NSString *time = [formatter stringFromDate:[NSDate date]];
    
    //本地图片完整路径
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", time];
    NSString *fullPath = [NSString stringWithFormat:@"%@/%@", kFileCacheDirectory, fileName];
    
    //创建文件夹
    if (![self creatFileDirectoryWith:kFileCacheDirectory]) {
        //文件夹创建失败
        return @"";
    }
    //写入文件
    BOOL isSuccess = [[NSFileManager defaultManager] createFileAtPath:fullPath contents:imageData attributes:nil];
    
    //写入文件成功
    if (isSuccess) {
        return fileName;
    }
    //失败返回空字符串
    return @"";
}

+(NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length <= size) {
        return data;
    }
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < size) {
            min = compression;
        } else if (data.length > size * 0.9) {
            max = compression;
        } else {
            break;
        }
    }
    return data;
}

/**
 获取完整的文件路径名 - 绝对路径
 
 @param fileName 文件名
 */
+(NSString *)getFullFilePathWithFileName:(NSString *)fileName{
    //已经是完整的路径名
    if ([kSTRING(fileName) containsString:@"kFileCacheDirectory"]){
        return kSTRING(fileName);
    }
    //不完整的 - 拼接完整的
    NSString *fullPath = [NSString stringWithFormat:@"%@/%@",kFileCacheDirectory,fileName];
    return fullPath;
}

/**
 在指定目录下创建一个文件夹
 
 @param dirPath 文件夹路径
 */
+(BOOL)creatFileDirectoryWith:(NSString *)dirPath{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // fileExistsAtPath 判断一个文件或目录是否有效，isDirectory判断是否一个目录
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:dirPath isDirectory:&isDir];
    //如果文件夹不存在
    if (!(isDir == YES && existed == YES)){
        BOOL creatSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
        return creatSuccess;
    }
    //如果存在直接返回YES
    return YES;
}

/**
 解决拍照之后照片自动旋转90度wen
 
 @param image 图片
 @return 修复之后的图片
 */
+(UIImage *)fixOrientation:(UIImage *)image
{
    if (image.imageOrientation == UIImageOrientationUp) return image;
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (image.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, image.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    
    switch (image.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,
                                             CGImageGetBitsPerComponent(image.CGImage), 0,
                                             CGImageGetColorSpace(image.CGImage),
                                             CGImageGetBitmapInfo(image.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (image.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.width,image.size.height), image.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

/**
 window上菊花
 */
+(void)showHudOnWindow
{
    dispatch_main_async_safe(^{
        MBProgressHUD *hod = [kAppWindow viewWithTag:kHudTag];
        if (!hod){
            hod =  [MBProgressHUD showHUDAddedTo:kAppWindow animated:YES];
        }
        hod.detailsLabel.text = kLocalString(@"加载中...");
        hod.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
        hod.backgroundView.color = [UIColor colorWithWhite:0.f alpha:.2f];
    });
}

/**
 window上菊花 自定义文案
 */
+(MBProgressHUD *)showHudOnWindowWith:(NSString *)message{
    __block NSString *messageStr = @"";
    __block MBProgressHUD *hod = nil;
    dispatch_main_async_safe(^{
        hod = [kAppWindow viewWithTag:kHudTag];
        if (!hod){
            hod =  [MBProgressHUD showHUDAddedTo:kAppWindow animated:YES];
            hod.tag = kHudTag;
        }
        messageStr = message.length > 0 ? message : kLocalString(@"加载中...");
        hod.detailsLabel.text = messageStr;
        hod.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
        hod.backgroundView.color = [UIColor colorWithWhite:0.f alpha:.2f];
    });
    return hod;
}

/**
 隐藏window上菊花
 */
+(void)hideHudOnKeyWindow
{
    dispatch_main_async_safe(^{
        [MBProgressHUD hideHUDForView:kAppWindow animated:YES];
    });
}

/**
 默认菊花
 
 @param view - 父视图
 */
+(void)showHudOnView:(UIView *)view
{
    dispatch_main_async_safe(^{
        MBProgressHUD *hod = [view viewWithTag:kHudTag];
        if (hod) return;
        hod = [MBProgressHUD showHUDAddedTo:view animated:YES];
        hod.tag = kHudTag;
        hod.detailsLabel.text = kLocalString(@"加载中...");
    });
}

/**
 自定义文案菊花
 
 @param view - 父视图
 @param message - 文案
 */
+(MBProgressHUD *)showHudOnView:(UIView *)view message:(NSString *)message{
    __block NSString *messageStr = @"";
    __block MBProgressHUD *hod = nil;
    dispatch_main_async_safe(^{
        if (!hod){
            hod =  [MBProgressHUD showHUDAddedTo:view animated:YES];
        }
        messageStr = message.length > 0 ? message : kLocalString(@"加载中...");
        hod.detailsLabel.text = messageStr;
    });
    return hod;
}

+(void)hideHudOnView:(UIView *)view
{
    [MBProgressHUD hideHUDForView:view animated:YES];
}

/**
 默认文案缺省图
 
 @param view 父视图
 */
+(void)showDefaultImageOnView:(UIView *)view
{
    [self showDefaultImageOnView:view message:@""];
}

+(BOOL)isFullScreenIphone {
    BOOL isFullIphone = NO;
    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
        if (mainWindow.safeAreaInsets.bottom > 0.0) {
            isFullIphone = YES;
        }
    }
    
    return isFullIphone;
}

/**
 隐藏缺省图
 
 @param view 父视图
 */
+(void)hideDefaultImageOnView:(UIView *)view{
    UIView *defaultView = [view viewWithTag:kDefaultViewTag];
    if (defaultView) {
        [defaultView removeFromSuperview];
        defaultView = nil;
    }
}

/**
 默认图 文案自定义
 
 @param view - 父视图
 @param message - 文案
 */
+(void)showDefaultImageOnView:(UIView *)view message:(NSString *)message
{
    if ([view viewWithTag:kDefaultViewTag]) {
        return;
    }
    NSString *imageUrl = @"default_bg";
    UIImage *image = [UIImage imageNamed:imageUrl];
    UIView *defaultView = [[UIView alloc] initWithFrame:view.bounds];
    defaultView.tag =  kDefaultViewTag;
    UIView *iconView = [[UIView alloc] init];
    defaultView.backgroundColor = view.backgroundColor;
    UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, image.size.width, image.size.height)];
    
    [iconImageView setImage:image];
    [view addSubview:defaultView];
    [defaultView addSubview:iconView];
    [iconView addSubview:iconImageView];
    
    //提示
    UILabel *titleLabel = [[UILabel alloc] init];
    [titleLabel setText:kSTRING(message)];
    [titleLabel setFont:kFont(20)];
    [titleLabel setTextColor:OSColor_3];
    [titleLabel sizeToFit];
    [iconView addSubview:titleLabel];
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(defaultView.mas_centerX);
        make.top.equalTo(iconImageView.mas_bottom).offset(15);
    }];
    CGFloat width = iconImageView.width;
    CGFloat height  = iconImageView.height + 15 + titleLabel.height;
    defaultView.frame = CGRectMake((defaultView.width-width)/2, (defaultView.height-height)/2, width, height);
}

//截屏并且保存到相册
+(void)screenShotsAndSaveComplete:(void(^)(UIImage * img)) complete{
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        if(complete){
            complete(nil);
        }
        return;
    }
    
    if (status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status != PHAuthorizationStatusAuthorized) {
                if(complete){
                    complete(nil);
                }
                return;
            }
        }];
    }
    
    CGSize imageSize = [[UIScreen mainScreen] bounds].size;
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow * window in [[UIApplication sharedApplication] windows]) {
        if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {
            CGContextSaveGState(context);

            CGContextTranslateCTM(context, [window center].x, [window center].y);

            CGContextConcatCTM(context, [window transform]);

            CGContextTranslateCTM(context, -[window bounds].size.width*[[window layer] anchorPoint].x, -[window bounds].size.height*[[window layer] anchorPoint].y);

            [[window layer] renderInContext:context];

            CGContextRestoreGState(context);
        }
    }

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
    NSLog(@"Suceeded!");

    if(complete){
        complete(image);
    }
}

//只截屏
+(void)screenShotsComplete:(void(^)(UIImage * img)) complete{
    CGSize imageSize = [[UIScreen mainScreen] bounds].size;
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow * window in [[UIApplication sharedApplication] windows]) {
        if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {
            CGContextSaveGState(context);

            CGContextTranslateCTM(context, [window center].x, [window center].y);

            CGContextConcatCTM(context, [window transform]);

            CGContextTranslateCTM(context, -[window bounds].size.width*[[window layer] anchorPoint].x, -[window bounds].size.height*[[window layer] anchorPoint].y);

            [[window layer] renderInContext:context];

            CGContextRestoreGState(context);
        }
    }

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"Suceeded!");

    if(complete){
        complete(image);
    }
}

//调用系统分享当前截图
+(void)shareWithTitle:(NSString *)title vc:(UIViewController *)vc{
    
    NSString *testToShare = title;
    [OSTool screenShotsComplete:^(UIImage * _Nonnull img) {
        UIImage *imageToShare = img;
        NSArray *activityItems = @[testToShare,imageToShare];
        UIActivityViewController *activityVc = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
        [vc presentViewController:activityVc animated:YES completion:nil];
        activityVc.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
            if (completed) {
                NSLog(@"分享成功");
            }else{
                NSLog(@"分享取消");
            }
        };
    }];
}

/**
 获取当前视图的VC层
 
 @return
 */
+(UIViewController *)getCurrentUIVC
{
    UIViewController  *superVC = [self seg_getCurrentVC];
    
    if ([superVC isKindOfClass:[UITabBarController class]]) {
        
        UIViewController  *tabSelectVC = ((UITabBarController*)superVC).selectedViewController;
        
        if ([tabSelectVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)tabSelectVC).viewControllers.lastObject;
        }
        return tabSelectVC;
    }else
        if ([superVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)superVC).viewControllers.lastObject;
        }
    return superVC;
    
}

+(UIViewController *)seg_getCurrentVC{
    
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    if ([window subviews].count > 0) {
        UIView *frontView = [[window subviews] objectAtIndex:0];
        id nextResponder = [frontView nextResponder];
        
        if ([nextResponder isKindOfClass:[UIViewController class]])
            result = nextResponder;
        else{
            result = window.rootViewController;
        }
    }
    return result;
}

@end
